<template>
  <div class="app-container">
    <!--查询-->
    <el-form :inline="true" :model="contractQuery" class="demo-form-inline">
      <el-form-item label="工号">
        <el-select v-model="contractQuery.userId" filterable clearable placeholder="输入名字">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" style="margin: 10px" @click="handleAddContract">new</el-button>

    <el-table :data="contractList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="名称" width="180">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="term" label="合同期限(单位:月)" width="180">
        <template slot-scope="scope">
          {{ scope.row.term }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="conversation" label="转正日期">
        <template slot-scope="scope">
          <el-date-picker readonly v-model="scope.row.conversation" type="date" placeholder="转正日期"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="begin" label="开始时间">
        <template slot-scope="scope">
          <el-date-picker readonly v-model="scope.row.begin" type="date" placeholder="开始时间"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="end" label="结束时间">
        <template slot-scope="scope">
          <el-date-picker readonly v-model="scope.row.end" type="date" placeholder="结束时间"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="fileUrl" label="文件">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="downloadFile(scope.row.fileUrl)">
            下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getContracts"
      />
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit contract':'New contract'">
      <el-form :model="contract" label-width="90px" label-position="left">
        <el-form-item label="名字" prop="name">
          <el-select v-model="contract.userId" filterable clearable placeholder="输入名字">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转正日期" prop="conversation">
          <el-date-picker
            v-model="contract.conversation"
            type="date"
            value-format="timestamp"
            placeholder="转正日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="begin">
          <el-date-picker
            v-model="contract.begin"
            type="date"
            value-format="timestamp"
            placeholder="开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end">
          <el-date-picker
            v-model="contract.end"
            type="date"
            value-format="timestamp"
            placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件" prop="fileId">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            accept="image/jpeg,image/jpg,image/png,pdf"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :http-request="upload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmContract">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getUserList } from '@/api/user'
import { addContract, deleteContract, getContracts } from '@/api/contract'
import { deepClone } from '@/utils'
import { download, upload } from '@/api/file'

const defaultContract = {
  id: '',
  userId: '',
}

export default {
  name: 'ContractManager',
  data() {
    return {
      contract: {},
      dialogVisible: false,
      dialogType: 'new',
      contractList: [],
      contractQuery: {},
      userList: [],
      fileList: [],
      total: 100,
      page: 1,
      limit: 20,
    }
  },
  created() {
    this.getContracts()
    this.getUserList()
  },
  methods: {
    async getContracts(page = 1) {
      const offset = this.limit * (page - 1);
      const res = await getContracts(this.contractQuery, offset, this.limit)
      this.contractList = res.data.rows
      this.total = res.data.total
    },
    onSubmit() {
      this.getContracts()
    },
    async getUserList() {
      const res = await getUserList()
      this.userList = res.data
    },
    handleAddContract() {
      this.contract = Object.assign({}, defaultContract)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.fileList = []
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.contract = deepClone(scope.row)
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteContract(row.id, 'FALSE')
          this.contractList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmContract() {
      if (this.contract.fileId === '' || this.contract.fileId === undefined) {
        this.$message({
          message: '信息需填写完整',
          type: 'warning'
        })
        return
      }
      await addContract(this.contract)
      await this.getContracts()
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功",
        type: 'success'
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.contract.fileId = ''
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    async upload(params) {
      let form = new FormData();
      this.$refs.upload.uploadFiles.forEach((file) => {
        form.append("file", file.raw);
      });
      await upload(form).then((res) => {
        this.contract.fileId = res.data
        // console.log(this.contract.fileId)
      })
    },
    async downloadFile(fileName) {
      await download(fileName).then(res => {           //定义文件名等相关信息
        const blob = res
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
